package com.sneakxy.mybatis.commons.orm.mapping;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.scripting.xmltags.DynamicContext;
import org.apache.ibatis.scripting.xmltags.ExpressionEvaluator;
import org.apache.ibatis.scripting.xmltags.SqlNode;
import org.apache.ibatis.scripting.xmltags.TextSqlNode;

import com.sneakxy.mybatis.commons.orm.generation.GenerationManager;

/**
 * 判断构造节点
 * @author 潜行的虚影
 */
public class MybatisColumnSqlNode implements SqlNode {

	private final ExpressionEvaluator evaluator;
	
	private GenerationManager generationManager;
	
	private List<MybatisColumn> columns;
	
	private String seperator;
	
	public MybatisColumnSqlNode(GenerationManager generationManager, List<MybatisColumn> columns, String seperator) {
		this.generationManager = generationManager;
		this.columns = columns;
		this.seperator = seperator;
		this.evaluator = new ExpressionEvaluator();
	}
	
	/* (non-Javadoc)
	 * @see org.apache.ibatis.scripting.xmltags.SqlNode#apply(org.apache.ibatis.scripting.xmltags.DynamicContext)
	 */
	@Override
	public boolean apply(DynamicContext context) {
		boolean first = true;
		String test = null;
		for(MybatisColumn column: columns) {
			if(!column.isReadonly()) {
				test = StringUtils.join(column.getPropertyPath(), " != null");
				if(evaluator.evaluateBoolean(test, context.getBindings())) {
					new TextSqlNode(
							StringUtils.join(
									first ? "": seperator,
									generationManager.formatColumnName(column.getColumn()), 
									"=#{", column.getPropertyPath(), "}")).apply(context);
					first = false;
				}
			}
		}
		return false;
	}

}
